<template>
  <div class="product-detail-page">
    <el-header class="header" height="70px">
      <div class="header-content">
        <div class="logo">
          <h1 @click="$router.push('/')" style="cursor: pointer;">周周淘商城</h1>
        </div>
        <div class="nav-actions">
          <el-button @click="$router.push('/cart')" type="primary" plain>
            <el-icon><ShoppingCart /></el-icon>
            购物车
          </el-button>
          <template v-if="userStore.token">
            <el-dropdown @command="handleUserCommand">
              <el-button type="primary">
                {{ userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <el-button @click="$router.push('/login')" type="primary">登录</el-button>
            <el-button @click="$router.push('/register')" plain>注册</el-button>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="main-content">
      <div class="page-header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="$router.push('/')">首页</el-breadcrumb-item>
          <el-breadcrumb-item @click="$router.push('/products')">商品列表</el-breadcrumb-item>
          <el-breadcrumb-item>商品详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div v-if="product" class="product-detail">
        <el-row :gutter="40">
          <el-col :span="12">
            <div class="product-image">
              <img :src="product.image" :alt="product.name">
            </div>
          </el-col>
          <el-col :span="12">
            <div class="product-info">
              <h1 class="product-name">{{ product.name }}</h1>
              <p class="product-brand">品牌：{{ product.brand }}</p>
              <p v-if="product.spec && product.spec !== '{}' && product.spec.trim() !== ''" class="product-spec">规格：{{ product.spec }}</p>
              <div class="product-price">
                <span class="price">¥{{ formatPrice(product.price) }}</span>
              </div>
              <div class="product-stats">
                <span class="sold">已售 {{ product.sold }}</span>
                <span class="rating">⭐ 4.5</span>
              </div>
              <div class="product-actions">
                <el-input-number
                  v-model="quantity"
                  :min="1"
                  :max="99"
                  size="large"
                />
                <el-button
                  type="primary"
                  size="large"
                  @click="addToCart"
                  :disabled="!userStore.token"
                >
                  加入购物车
                </el-button>
                <el-button
                  type="danger"
                  size="large"
                  @click="buyNow"
                  :disabled="!userStore.token"
                >
                  立即购买
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div v-else class="loading">
        <el-skeleton :rows="10" animated />
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getItemById } from '@/api/item'
import type { ItemDTO } from '@/api/item'
import { addItem2Cart } from '@/api/cart'
import type { CartFormDTO } from '@/api/cart'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const product = ref<ItemDTO | null>(null)
const quantity = ref(1)

// 格式化价格（将分转换为元）
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2)
}

const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

const addToCart = async () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!product.value) {
    ElMessage.error('商品信息获取失败，无法添加到购物车');
    return;
  }

  try {
    const cartItem: CartFormDTO = {
      itemId: product.value.id!,
      num: quantity.value,
      name: product.value.name,
      spec: product.value.spec,
      price: product.value.price,
      image: product.value.image
    };
    await addItem2Cart(cartItem);
    ElMessage.success('已添加到购物车');
  } catch (error) {
    console.error('添加购物车失败:', error);
    ElMessage.error('添加购物车失败');
  }
}

const buyNow = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  router.push('/checkout')
}

const loadProduct = async () => {
  try {
    const productId = Number(route.params.id)
    const response = await getItemById(productId)
    const responseData = response.data

    // 检查是否是新的API格式（包含code字段）
    if (responseData && responseData.code !== undefined) {
      // 新格式：{code: 200, msg: "OK", data: {...}}
      if (responseData.code === 200 && responseData.data) {
        product.value = responseData.data
      } else {
        ElMessage.error(responseData.msg || '加载商品详情失败')
      }
    } else {
      // 旧格式：直接返回数据对象
      if (responseData && responseData.id) {
        product.value = responseData
      } else {
        ElMessage.error('加载商品详情失败')
      }
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  }
}

onMounted(() => {
  loadProduct()
})
</script>

<style scoped>
.product-detail-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo h1 {
  color: #409eff;
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.product-detail {
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image img {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
}

.product-name {
  font-size: 28px;
  color: #333;
  margin: 0 0 15px 0;
}

.product-brand {
  color: #666;
  margin: 10px 0;
  font-size: 16px;
}

.product-spec {
  color: #666;
  margin: 10px 0;
  font-size: 16px;
}

.product-price {
  margin: 20px 0;
}

.price {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
}

.product-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  color: #666;
}

.product-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}
</style>
